import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask> {//任务
    private Runnable task;
    private long time;//任务执行的具体时间，当前时间+等待时间

    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTimerTask myTimerTask) {
        return (int)(this.time - myTimerTask.time);
    }

    public long getTime() {
        return this.time;
    }

    public void run() {
        this.task.run();
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    private Object locker = new Object();

    public void schedule(Runnable task, long time) {
        synchronized(locker) {
            MyTimerTask myTimerTask= new MyTimerTask(task, System.currentTimeMillis() + time);
            queue.offer(myTimerTask);
            locker.notify();//当队列中有任务时，唤醒while (queue.isEmpty())  locker.wait();
        }

    }

    public MyTimer(){
        Thread thread = new Thread(() -> {
            synchronized(locker) {
                while (true) {
                    while (queue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask myTimerTask = queue.peek();
                    if (System.currentTimeMillis() < myTimerTask.getTime()) {
                        try {
                            locker.wait(myTimerTask.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        myTimerTask.run();
                        queue.poll();
                    }
                }
            }
        });
        thread.start();
    }
}

public class Demo3 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(3000);
            }
        }, 3000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(2000);
            }
        }, 2000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(1000);
            }
        }, 1000);

        System.out.println("main");
    }
}
